package com.flymobi.util;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.FilterDispatcher;

@SuppressWarnings("deprecation")
public class SetCharacterFilterDispatcher extends FilterDispatcher {
	protected String encoding = null;
	protected FilterConfig filterConfig = null;
	protected boolean ignore = true;

	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		if ((this.ignore) || (req.getCharacterEncoding() == null)) {
			if(req.getRequestURI().indexOf("/admin")!=-1){
				req.setCharacterEncoding(encoding);
			}else{
				req.setCharacterEncoding("UTF-8");
				req.getParameter("id");
				/*String key=req.getParameter("key");
				try {
					System.out.println("1:key="+key);
					System.out.println("2:key="+new String(key.getBytes("ISO-8859-1"),"utf-8"));
					System.out.println("3:key="+new String(key.getBytes(),"utf-8"));
					System.out.println("4:key="+new String(key.getBytes(),"gbk"));
					System.out.println("5:key="+new String(key.getBytes("ISO-8859-1"),"gbk"));
					System.out.println("6:key="+new String(key.getBytes("utf-8"),"gbk"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}*/
			}
			if(req.getMethod().equalsIgnoreCase("get"))   
	        {   
				req = new GetHttpServletRequestWrapper(req,encoding);   
	        }
		}
	    super.doFilter(req, response, chain);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		super.init(filterConfig);
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		if (value == null)
			this.ignore = true;
		else if (value.equalsIgnoreCase("true"))
			this.ignore = true;
		else if (value.equalsIgnoreCase("yes"))
			this.ignore = true;
		else
			this.ignore = false;
	}

}